#include "mainwindow.h"
#include "log.h"
#include <stdio.h>
#include <stdlib.h>
#include <QApplication>
#include <QMutex>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    // 加锁
    static QMutex mutex;
    mutex.lock();

    QByteArray tmpMsg;
    QString strMsg;
    QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    switch(type)
    {
    case QtDebugMsg:
#if (LOG_LEVEL >= LOG_LEVEL_DEBUG)
       strMsg = QString(GRAY "[%1|%2|%3@%4] DEBUG:  " GREEN "%5" NONE "\n")
                .arg(strDateTime)
                .arg(context.file)
                .arg(context.function)
                .arg(context.line)
                .arg(msg);
#endif
        break;
    case QtInfoMsg:
#if (LOG_LEVEL >= LOG_LEVEL_INFO)
       strMsg = QString(GRAY "[%1|%2|%3@%4] INFO:  " BLUE "%5" NONE "\n")
                .arg(strDateTime)
                .arg(context.file)
                .arg(context.function)
                .arg(context.line)
                .arg(msg);
#endif
        break;
    case QtWarningMsg:
#if (LOG_LEVEL >= LOG_LEVEL_WARN)
        strMsg = QString(GRAY "[%1|%2|%3@%4] WARN:  " PURPLE "%5" NONE "\n")
                 .arg(strDateTime)
                 .arg(context.file)
                 .arg(context.function)
                 .arg(context.line)
                 .arg(msg);
#endif
        break;
    case QtCriticalMsg:
#if (LOG_LEVEL >= LOG_LEVEL_ERROR)
        strMsg = QString(GRAY "[%1|%2|%3@%4] ERROR:  " L_RED "%5" NONE "\n")
                 .arg(strDateTime)
                 .arg(context.file)
                 .arg(context.function)
                 .arg(context.line)
                 .arg(msg);
#endif
        break;
    case QtFatalMsg:
#if (LOG_LEVEL >= LOG_LEVEL_FATAL)
        strMsg = QString(GRAY "[%1|%2|%3@%4] FATAL:  " RED "%5" NONE "\n")
                 .arg(strDateTime)
                 .arg(context.file)
                 .arg(context.function)
                 .arg(context.line)
                 .arg(msg);
#endif
        break;
    default:
        break;
    }

    tmpMsg = strMsg.toLocal8Bit();
    fprintf(stdout,"%s",tmpMsg.data());
    fflush(stdout);

    // 输出信息至文件中（读写、追加形式）
//    QFile file("log.txt");
//    file.open(QIODevice::ReadWrite | QIODevice::Append);
//    QTextStream stream(&file);
//    stream << strMessage << "\r\n";
//    file.flush();
//    file.close();

    // 解锁
    mutex.unlock();
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(myMessageOutput);
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
